package com.yuerlive.rainbow.utils;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.yuerlive.rainbow.API;
import com.yuerlive.rainbow.RainbowApp;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * Created by arvin on 2016/10/15.
 */

public class DownloadImage {
    BlockingDeque<Runnable> mTaskQueue = new LinkedBlockingDeque<>(4);
    ThreadPoolExecutor executor = new ThreadPoolExecutor(4, 8, 30, TimeUnit.SECONDS, mTaskQueue, new ThreadPoolExecutor.DiscardPolicy());
    String mSaveDir = Environment.getExternalStorageDirectory() + "/" + RainbowApp.getContext().getPackageName() + "/cache/img/gift/";
    //    String mTmpPath = Environment.getExternalStorageDirectory() + "/com.miqtech.master.wylive/cache/img/temp/";
    private int bounds = DeviceUtils.dp2px(RainbowApp.getContext(), 15);


    public void download(String url) {
        if (exists(url)) return;
        if (url == null) return;
        if (!url.startsWith("http")) {
            url = API.IMAGE_HOST + url;
        }
        final String savaPath = mSaveDir + url.replaceAll("/", "").replaceAll(".jpg", "").replaceAll(".gif", "").replaceAll(".png", "").replaceAll("http:img.wangyuhudong.com", "");
        final String finalUrl = url;

        executor.execute(new Runnable() {
            @Override
            public void run() {
                InputStream inStream = null;
                FileOutputStream fos = null;
                try {
                    File saveDir = new File(mSaveDir);
                    if (!saveDir.exists()) {
                        saveDir.mkdirs();
                    }
                    fos = new FileOutputStream(savaPath);
                    URL imgUrl = new URL(finalUrl);

                    HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
                    conn.setConnectTimeout(50 * 1000);
                    conn.setRequestMethod("GET");
                    inStream = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inStream);
                    bitmap = Bitmap.createScaledBitmap(bitmap, bounds, bounds, false);

                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    CloseUtil.close(inStream);
                    CloseUtil.close(fos);
                }

            }
        });
    }

    public void download(String url, boolean scale) {
        if (exists(url)) return;
        url = API.IMAGE_HOST + url;
        if (url == null) return;
        final String savaPath = mSaveDir + url.replaceAll("/", "");
        final String finalUrl = url;

        executor.execute(new Runnable() {
            @Override
            public void run() {
                InputStream inStream = null;
                FileOutputStream fos = null;
                try {
                    File saveDir = new File(mSaveDir);
                    if (!saveDir.exists()) {
                        saveDir.mkdirs();
                    }
                    fos = new FileOutputStream(savaPath);
                    URL imgUrl = new URL(finalUrl);

                    HttpURLConnection conn = (HttpURLConnection) imgUrl.openConnection();
                    conn.setConnectTimeout(50 * 1000);
                    conn.setRequestMethod("GET");
                    inStream = conn.getInputStream();
                    Bitmap bitmap = BitmapFactory.decodeStream(inStream);
                    bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight(), false);

                    bitmap.compress(Bitmap.CompressFormat.JPEG, 50, fos);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    CloseUtil.close(inStream);
                    CloseUtil.close(fos);
                }

            }
        });
    }

    private static volatile DownloadImage mInstance;

    private DownloadImage() {
    }

    public static DownloadImage getInstance() {
        if (mInstance == null) {
            synchronized (DownloadImage.class) {
                if (mInstance == null) {
                    mInstance = new DownloadImage();
                }
            }
        }
        return mInstance;
    }

    Map<String, Bitmap> mGifts = new HashMap<>();

    public Bitmap getBitmap(String url) {
        String path = mSaveDir + (API.IMAGE_HOST + url).replaceAll("/", "").replaceAll(".jpg", "").replaceAll(".gif", "").replaceAll(".png", "")
                .replaceAll("http:img.wangyuhudong.com", "");
        if (mGifts.containsKey(path)) {
            return mGifts.get(path);
        } else {
            Bitmap b = BitmapFactory.decodeFile(path);
            mGifts.put(path, b);
            return b;
        }

    }

    private boolean exists(String url) {
        File file = new File(mSaveDir, (API.IMAGE_HOST + url).replaceAll("/", "").replaceAll(".jpg", "").replaceAll(".gif", "").replaceAll(".png", "").replaceAll("http:img.wangyuhudong.com", ""));
        if (file.exists()) {
            return true;
        }
        return false;
    }

}
